// index.js
// 获取应用实例
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp();
const db = wx.cloud.database();
const _ = db.command
Page({
  data: {
    appointment_status_color: '#D24D57',
    user_status: true,
    userInfo: []
  },
  myconfirm(event) {
    let that = this
    let status = event.currentTarget.dataset.status
    let startTime = new Date(event.currentTarget.dataset.starttime)
    let seat_id = event.currentTarget.dataset.seat_id
    let index = event.currentTarget.dataset.index
    let appointId = event.currentTarget.id
    if(new Date()<new Date(startTime.valueOf() - 10 * 60 * 1000)){
      Dialog.alert({
        message: '请在开始时间前10分钟内签到'
      })
    }else{
      if (status != "已失效" && status != "学习中") {
        if (startTime > new Date()) { //时间未到,可以签到
          wx.scanCode({
            onlyFromCamera: true,
            success(res) {
              if (res.result == seat_id) {
                db.collection("appointment_time").where({
                  _id: appointId
                }).update({
                  data: {
                    isCheck: true
                  }
                }).then(res => {
                  Dialog.alert({
                    message: '签到成功'
                  })
                  if (that.data.userInfo[0].id == appointId) {
                    that.setData({
                      ['userInfo[0].status']: '学习中',
                      ['userInfo[0].color']: ' #26A65B'
                    })
                  } else {
                    that.setData({
                      ['userInfo[1].status']: '学习中',
                      ['userInfo[1].color']: ' #26A65B'
                    })
                  }
                })
              } else {
                Dialog.alert({
                  message: '座位不匹配'
                })
              }
            },
            fail(res) {
              Dialog.alert({
                message: '座位不匹配'
              })
            }
          })
        } else { //时间到了,失效,还没测试___
          Dialog.alert({
            message: "已超过签到时间"
          })
          this.setData({
            [`userInfo[${index}].status`]: "已失效"
          })
        }
      } else {
        Dialog.alert({
          message: status
        })
      }
    }
  },
  //取消预约
  /**
   * 未超时 已签到 的取消:加入记录
   * 未超时 未签到 的取消:减少积分
   * 已超时 已签到 的取消:加入记录
   * 已超时 未签到 的取消:减大积分
   */
  mycancel(event) {
    db.collection("appointment_time").where({
      "_id": event.currentTarget.id
    }).get().then(res => {

      if(res.data[0].isCheck){
        let s = new Date(res.data[0].start_time)
        let time = (new Date() - s) / 1000 / 60
        Dialog.confirm({
          title: '取消预约',
          message: '已学习' + time + '分钟,是否取消预约',
        }).then(() => {
          //确认取消
          db.collection("appointment_time").where({
            "_id": event.currentTarget.id
          }).remove().then(rem => {
            // 上传预约记录
            let d = res.data[0]
            db.collection("appointment_log").add({
              data: {
                end_time: d.end_time,
                start_time: d.start_time,
                floor: d.floor,
                name: d.name,
                position: d.position
              }
            })
            this.onLoad()
            Notify({
              type: 'success',
              message: '退订成功'
            });
          })
        }).catch(() => {
          // on cancel
        });
      }else{
        Dialog.confirm({
          message: '占座未签到，扣除十积分',
        }).then(() => {
          // on close
          db.collection("appointment_time").where({
            "_id": event.currentTarget.id
          }).remove().then(res => {
            this.onLoad()
            Notify({
              type: 'success',
              message: '退订成功'
            });
          })
        }).catch(() => {
          // on cancel
        });
      }
      /**
      
      Dialog.alert({
        message: '占座未签到，扣除十积分',
      }).then(() => {
        // on close
        db.collection("appointment_time").where({
          "_id": event.currentTarget.id
        }).remove().then(res => {
          this.onLoad()
          Notify({
            type: 'success',
            message: '退订成功'
          });
        })
      })



       */

      // if (res.data[0].isCheck) {
      //   if (this.isInvaild(res)) { //签到后超时
      //     Dialog.alert({
      //       message: '占座未签到，扣除十积分',
      //     }).then(() => {
      //       db.collection("appointment_time").where({
      //         "_id": event.currentTarget.id
      //       }).remove().then(res => {
      //         this.onLoad()
      //         Notify({
      //           type: 'success',
      //           message: '退订成功'
      //         });
      //       })
      //     })
      //   } else {
      //     let s = new Date(res.data[0].start_time)
      //     let time = (new Date() - s) / 1000 / 60
      //     Dialog.confirm({
      //       title: '取消预约',
      //       message: '已学习' + time + '分钟,是否取消预约',
      //     }).then(() => {
      //       //确认取消
      //       db.collection("appointment_time").where({
      //         "_id": event.currentTarget.id
      //       }).remove().then(rem => {
      //         // 上传预约记录
      //         let d = res.data[0]
      //         db.collection("appointment_log").add({
      //           data: {
      //             end_time: d.end_time,
      //             start_time: d.start_time,
      //             floor: d.floor,
      //             name: d.name,
      //             position: d.position
      //           }
      //         })
      //         this.onLoad()
      //         Notify({
      //           type: 'success',
      //           message: '退订成功'
      //         });
      //       })
      //     }).catch(() => {
      //       // on cancel
      //     });
      //   }






      // } else if (res.data[0].isCheck) {




      //   Dialog.confirm({
      //     title: '取消预约',
      //     message: '未签到取消预约将扣除5点积分',
      //   }).then(() => {
      //     //确认取消
      //     db.collection("appointment_time").where({
      //       "_id": event.currentTarget.id
      //     }).remove().then(rem => {
      //       this.onLoad()
      //       Notify({
      //         type: 'success',
      //         message: '退订成功'
      //       });
      //     })
      //   }).catch(() => {
      //     // on cancel
      //   });



      // }





    })
  },
  onShow() {
    this.onLoad()
  },
  onLoad() {
    let date = new Date();
    db.collection("appointment_time").where({
      "_openid": app.globalData.openId
    }).get().then(res => {
      this.setData({
        userInfo: []
      })
      for (let i = 0; i < res.data.length; i++) {
        let s = new Date(res.data[i].start_time)
        let e = new Date(res.data[i].end_time)
        let day_ = '';
        if (s.getDate() == date.getDate()) {
          day_ = '今天'
        } else {
          day_ = '明天'
        }
        let s_min = s.getMinutes()
        let e_min = e.getMinutes()
        if (parseInt(parseInt(s.getMinutes())) < 10) {
          s_min = '0' + s.getMinutes()
        }
        if (parseInt(parseInt(e.getMinutes())) < 10) {
          e_min = '0' + e.getMinutes()
        }
        let show = this.data.userInfo;
        let status
        let color
        if (res.data[i].isCheck) {
          status = "学习中"
          color="#26a65b"
        } else {
          color="#D24D57"
          if (s < new Date()) {
            status = "已失效"
          } else {
            status = "请在" + day_ + s.getHours() + ':' + s_min + "前签到"
          }
        }
        let seat_ = {
          day: day_,
          start: s.getHours() + ':' + s_min,
          end: e.getHours() + ':' + e_min,
          position: res.data[i].position,
          status: status,
          floor: res.data[i].floor,
          id: res.data[i]._id,
          color: color,
          start_time: res.data[i].start_time,
          end_time: res.data[i].end_time,
          seat_id: res.data[i].seat_id
        }
        show.push(seat_)
        this.setData({
          userInfo: show
        })
      }
    })

    //监控公告
    let titleBar = this.selectComponent("#titleBar")
    db.collection("notifyMessage").watch({
     onChange: res=>{
         
         if(res.docChanges.length == 0){
             titleBar.update("暂无通知")
         }else if(res.docChanges[0].dataType == 'init'){
             if(res.docs.length != 0){
                 titleBar.update(res.docs[res.docs.length -1].message)
             }else{
                 titleBar.update("暂无通知")
             }
         }else if(res.docChanges[0].dataType == 'add'){
             titleBar.update("新通知："+res.docChanges[0].doc.message)
         }else if(res.docChanges[0].dataType == 'remove'){
             if(res.docs.length != 0){
                 titleBar.update(res.docs[res.docs.length -1].message)
             }else{
                 titleBar.update("暂无通知")
             }
         }
     },
     onError:res => {
     }
   })
  }
})